//
//  ZGLCalculatorClass.m
//  ZeegingLottery
//
//  Created by 李曌 on 2018/7/9.
//  Copyright © 2018年 蒂埃里. All rights reserved.
//

#import "ZGLCalculatorClass.h"


@implementation ZGLCalculatorClass

+ (instancetype)sharedInstance
{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    
    return instance;
}


//砌betContentJSON
- (NSString *)betContentJSONWith:(NSArray <ZGLAgainstModel *>*)JSONArray
{
    NSString *JSON = @"[]";
    NSMutableArray *json = [NSMutableArray array];
    if (JSONArray.count >= 2) {
        
        NSDictionary *MatchDict = [NSMutableDictionary dictionary];
        for (ZGLAgainstModel *model in JSONArray) {
            DLog(@"%@",model);
            
            NSString *matchid = model.id;
            NSString *matchkey = model.matchkey;
            NSString *matchtime = model.matchtime;
            NSString *handicap = model.hhad.Handicap;
            NSString *guts = @(model.guts).stringValue;
            NSMutableArray *betContent = model.betContentArray;
            
            MatchDict = @{
                          
                          @"betContent":betContent,
                          @"matchid"   :matchid,
                          @"matchkey"  :matchkey,
                          @"matchtime" :matchtime,
                          @"handicap"  :handicap,
                          @"guts"      :guts
                          
                          
                          };
            [json addObject:MatchDict];
        }
        
        JSON = [self convertToJsonData:json];
        DLog(@"json--%@",JSON);
        
        
    }
    return JSON;
}




#pragma mark - 比赛注数及金额计算
/**
 * @brief 比赛注数及金额计算
 *
 * @param betContentJSON NSString类型的JSON格式的投注内容，参看李濠的文档.输入示例：
 * NSString *json=@"
 [
 {\"matchid\":837160,\"matchkey\":\"20180501002\",\"handicap\":\"+1\",\"guts\":0,\"betContent\":
 [{\"id\":354,\"selection\":3,\"odds\":\"2.00\"},
 {\"id\":269,\"selection\":3,\"odds\":\"1.12\"}]
 },
 {\"matchid\":837162,\"matchkey\":\"20180501005\",\"handicap\":\"-2\",\"guts\":0,\"betContent\":
 [{\"id\":354,\"selection\":3,\"odds\":\"2.34\"},
 {\"id\":269,\"selection\":1,\"odds\":\"3.21\"}]
 }
 ]";
 * @param ggType 过关方式，"3001;"表示3串1，"8127;"表示8串127（不要漏了分号），可以同时以多种过关方式投注，直接拼接即可："3001;4001;8127;"
 * @param times 投注倍数
 * @param lotteryId 彩种ID，目前支持竞彩足球id=46
 *
 * @return 返回一个字典，包括了3个key-value：min、max、betNum.
 */
- (NSDictionary *)calculator:(NSString *)betContentJSON ggType:(NSString *)ggType times:(int)times lotteryId:(int)lotteryId
{
    //过关方式转成500用的格式
    NSArray *ggTypeArray=[ggType componentsSeparatedByString:@";"];
    NSMutableString *ggTypeFormat=[[NSMutableString alloc] init];
    for(NSString* ggTypeObj in ggTypeArray){
        if([ggTypeObj length]!=4){
            continue;
        }
        else{
            NSString *thisGGTypeFormat=[[NSString alloc] initWithFormat:@"%@*%d;",[ggTypeObj substringToIndex:1],[[ggTypeObj substringFromIndex:1] intValue]];
            [ggTypeFormat appendString:thisGGTypeFormat];
        }
    }
    //NSString *ggTypeFormat=[[NSString alloc] initWithFormat:@"%@*%d",[ggType substringToIndex:1],[[ggType substringFromIndex:1] intValue]];
    char *c_ggtype=(char *)[ggTypeFormat UTF8String];
    //彩种id
    int i_lot=(int)lotteryId;
    //投注内容，转成500用的格式
    char *c_bet=(char *)[[self betContentJSONto500String:betContentJSON] UTF8String];
    //是否混合
    int ismix=0;
    //是否重复
    int isdupl=0;
    //出参：最小奖金
    double d_min = 0.0;
    //出参：最大奖金
    double d_max = 0.0;
    //出参：注数
    long l_stack = 0;
    //拆单结果，不用可以传空
    //char c_betlist[1000];
    //调用函数计算
    int ret = api_calc_bet(i_lot, c_ggtype, c_bet, ismix, isdupl, &d_min, &d_max, &l_stack, NULL);
    //若返回0则表示成功，否则失败
    if(ret==0){
        NSString *minPrize=[[NSString alloc] initWithFormat:@"%f",(d_min*2*times)];
        NSString *maxPrize=[[NSString alloc] initWithFormat:@"%f",(d_max*2*times)];
        NSString *betNum=[[NSString alloc] initWithFormat:@"%ld",l_stack];
        NSDictionary * result=[[NSDictionary alloc] initWithObjectsAndKeys:minPrize,@"min_prize",maxPrize,@"max_prize",betNum,@"bet_num", nil];
        return result;
    }
    else{
        return false;
    }
}

#pragma mark - 投注内容JSON格式化成奖金计算方法的字符串格式

- (NSString *)betContentJSONto500String: (NSString *)betContentListJSON
{
    NSString * concatenateBetContent=@"";
    if (betContentListJSON) {
        
        NSArray *betContentList=[NSJSONSerialization JSONObjectWithData:[betContentListJSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        //NSLog(@"JSON: %@",betContentList);
        for(NSDictionary* match in betContentList){
            NSString *abbrMatchKey=[[match objectForKey:@"matchkey"] substringFromIndex:8];
            NSString *handicap=[match objectForKey:@"handicap"];
            NSString *guts=[match objectForKey:@"guts"];
            NSString *betContent=@"";
            for(NSDictionary *selection in [match objectForKey:@"betContent"]){
                NSString *selectionString=[[NSString alloc] initWithFormat:@"%@#%@#%@/",[selection objectForKey:@"id"],[selection objectForKey:@"selection"],[selection objectForKey:@"odds"]];
                betContent=[betContent stringByAppendingString:selectionString];
            }
            betContent=[betContent substringToIndex:[betContent length]-1];
            NSString *lineOfBetContent=[[NSString alloc] initWithFormat:@"%@|%@|%@|%@;",abbrMatchKey,handicap,guts,betContent];
            concatenateBetContent=[concatenateBetContent stringByAppendingString:lineOfBetContent];
        }
    }
    return concatenateBetContent;
}


/*
 字典/数组转Json字符串
 */
-(NSString *)convertToJsonData:(id )dict
{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}


/*
 JSON字符串转化为字典
 */
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}



@end
